<template>
  <div class="dashboard">
    <!-- 欢迎区域 -->
    <div class="welcome-card">
      <div class="welcome-content">
        <h2>欢迎回来，{{ userStore.username }}！</h2>
        <p>今天是 {{ currentDate }}，{{ greeting }}</p>
      </div>
      <div class="welcome-actions">
        <el-button type="primary" @click="router.push('/news/management')">
          <el-icon><Document /></el-icon>
          发布动态
        </el-button>
        <el-button @click="router.push('/course/management')">
          <el-icon><Reading /></el-icon>
          管理课程
        </el-button>
      </div>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-grid">
      <div class="stat-card">
        <div class="stat-icon news">
          <el-icon><Document /></el-icon>
        </div>
        <div class="stat-content">
          <div class="stat-number">{{ statsData.news.total }}</div>
          <div class="stat-label">行业动态</div>
          <div class="stat-extra">
            <span class="pending">待审核: {{ statsData.news.pending }}</span>
          </div>
        </div>
      </div>

      <div class="stat-card">
        <div class="stat-icon course">
          <el-icon><Reading /></el-icon>
        </div>
        <div class="stat-content">
          <div class="stat-number">{{ statsData.courses.total }}</div>
          <div class="stat-label">培训课程</div>
          <div class="stat-extra">
            <span class="pending">待审核: {{ statsData.courses.pending }}</span>
          </div>
        </div>
      </div>

      <div class="stat-card">
        <div class="stat-icon meeting">
          <el-icon><Calendar /></el-icon>
        </div>
        <div class="stat-content">
          <div class="stat-number">{{ statsData.meetings.total }}</div>
          <div class="stat-label">会议活动</div>
          <div class="stat-extra">
            <span class="pending">待审核: {{ statsData.meetings.pending }}</span>
          </div>
        </div>
      </div>

      <div class="stat-card" v-if="userStore.isAdmin">
        <div class="stat-icon user">
          <el-icon><User /></el-icon>
        </div>
        <div class="stat-content">
          <div class="stat-number">{{ statsData.users.total }}</div>
          <div class="stat-label">注册用户</div>
          <div class="stat-extra">
            <span class="active">活跃: {{ statsData.users.active }}</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 图表和列表 -->
    <div class="dashboard-grid">
      <!-- 数据趋势图表 -->
      <div class="chart-card">
        <div class="card-header">
          <h3>内容发布趋势</h3>
          <el-radio-group v-model="chartPeriod" size="small">
            <el-radio-button label="week">最近7天</el-radio-button>
            <el-radio-button label="month">最近30天</el-radio-button>
          </el-radio-group>
        </div>
        <div class="chart-container">
          <v-chart class="chart" :option="chartOption" autoresize />
        </div>
      </div>

      <!-- 最新动态 -->
      <div class="list-card">
        <div class="card-header">
          <h3>最新动态</h3>
          <el-button type="text" @click="router.push('/news/management')">
            查看更多 <el-icon><ArrowRight /></el-icon>
          </el-button>
        </div>
        <div class="list-content">
          <div 
            v-for="item in recentNews" 
            :key="item.id" 
            class="list-item"
            @click="viewNewsDetail(item)"
          >
            <div class="item-content">
              <div class="item-title">{{ item.title }}</div>
              <div class="item-meta">
                <span class="author">{{ item.author }}</span>
                <span class="time">{{ formatTime(item.createTime) }}</span>
                <el-tag :type="getStatusType(item.status)" size="small">
                  {{ getStatusText(item.status) }}
                </el-tag>
              </div>
            </div>
            <div class="item-actions">
              <el-icon><ArrowRight /></el-icon>
            </div>
          </div>
          <div v-if="recentNews.length === 0" class="empty-state">
            <el-empty description="暂无数据" :image-size="100" />
          </div>
        </div>
      </div>
    </div>

    <!-- 快捷操作和待办事项 -->
    <div class="bottom-grid">
      <!-- 快捷操作 -->
      <div class="quick-actions-card">
        <div class="card-header">
          <h3>快捷操作</h3>
        </div>
        <div class="quick-actions">
          <div class="action-item" @click="router.push('/news/management')">
            <div class="action-icon">
              <el-icon><Plus /></el-icon>
            </div>
            <div class="action-text">发布动态</div>
          </div>
          <div class="action-item" @click="router.push('/course/management')">
            <div class="action-icon">
              <el-icon><Plus /></el-icon>
            </div>
            <div class="action-text">创建课程</div>
          </div>
          <div class="action-item" @click="router.push('/meeting/management')">
            <div class="action-icon">
              <el-icon><Plus /></el-icon>
            </div>
            <div class="action-text">组织会议</div>
          </div>
          <div class="action-item" v-if="userStore.isAdmin" @click="router.push('/user/management')">
            <div class="action-icon">
              <el-icon><UserFilled /></el-icon>
            </div>
            <div class="action-text">用户管理</div>
          </div>
        </div>
      </div>

      <!-- 待审核事项 -->
      <div class="pending-card" v-if="userStore.isAdmin">
        <div class="card-header">
          <h3>待审核事项</h3>
        </div>
        <div class="pending-list">
          <div class="pending-item" v-if="pendingStats.news > 0">
            <div class="pending-info">
              <el-icon><Document /></el-icon>
              <span>{{ pendingStats.news }} 条行业动态待审核</span>
            </div>
            <el-button type="text" @click="router.push('/news/management')">
              立即处理
            </el-button>
          </div>
          <div class="pending-item" v-if="pendingStats.courses > 0">
            <div class="pending-info">
              <el-icon><Reading /></el-icon>
              <span>{{ pendingStats.courses }} 个课程待审核</span>
            </div>
            <el-button type="text" @click="router.push('/course/management')">
              立即处理
            </el-button>
          </div>
          <div class="pending-item" v-if="pendingStats.meetings > 0">
            <div class="pending-info">
              <el-icon><Calendar /></el-icon>
              <span>{{ pendingStats.meetings }} 个会议待审核</span>
            </div>
            <el-button type="text" @click="router.push('/meeting/management')">
              立即处理
            </el-button>
          </div>
          <div v-if="pendingStats.news === 0 && pendingStats.courses === 0 && pendingStats.meetings === 0" class="no-pending">
            <el-icon><CircleCheck /></el-icon>
            <span>暂无待审核事项</span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/store'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { LineChart, BarChart } from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent
} from 'echarts/components'
import VChart from 'vue-echarts'
import dayjs from 'dayjs'

// 注册必要的组件
use([
  CanvasRenderer,
  LineChart,
  BarChart,
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent
])

const router = useRouter()
const userStore = useUserStore()

// 响应式数据
const chartPeriod = ref('week')
const recentNews = ref([])
const loading = ref(false)

const statsData = reactive({
  news: { total: 0, pending: 0, published: 0 },
  courses: { total: 0, pending: 0, published: 0 },
  meetings: { total: 0, pending: 0, published: 0 },
  users: { total: 0, active: 0, disabled: 0 }
})

const pendingStats = reactive({
  news: 0,
  courses: 0,
  meetings: 0
})

// 计算属性
const currentDate = computed(() => {
  return dayjs().format('YYYY年MM月DD日 dddd')
})

const greeting = computed(() => {
  const hour = new Date().getHours()
  if (hour < 9) return '早上好！'
  if (hour < 12) return '上午好！'
  if (hour < 14) return '中午好！'
  if (hour < 18) return '下午好！'
  return '晚上好！'
})

const chartOption = computed(() => {
  return {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross'
      }
    },
    legend: {
      data: ['行业动态', '培训课程', '会议活动']
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '行业动态',
        type: 'line',
        stack: 'Total',
        smooth: true,
        lineStyle: {
          color: '#409EFF'
        },
        data: [12, 13, 10, 13, 9, 23, 21]
      },
      {
        name: '培训课程',
        type: 'line',
        stack: 'Total',
        smooth: true,
        lineStyle: {
          color: '#67C23A'
        },
        data: [2, 2, 3, 5, 3, 3, 6]
      },
      {
        name: '会议活动',
        type: 'line',
        stack: 'Total',
        smooth: true,
        lineStyle: {
          color: '#E6A23C'
        },
        data: [3, 4, 3, 6, 5, 4, 8]
      }
    ]
  }
})

// 方法
const getStatusType = (status) => {
  const typeMap = {
    0: 'warning',
    1: 'success',
    2: 'danger'
  }
  return typeMap[status] || 'info'
}

const getStatusText = (status) => {
  const textMap = {
    0: '待审核',
    1: '已发布',
    2: '已拒绝'
  }
  return textMap[status] || '未知'
}

const formatTime = (time) => {
  return dayjs(time).format('MM-DD HH:mm')
}

const viewNewsDetail = (item) => {
  // 这里可以实现查看详情的逻辑
  console.log('查看详情:', item)
}

const loadDashboardData = async () => {
  try {
    loading.value = true
    
    // 并行加载各种数据
    const promises = []
    
    // 加载新闻统计和列表
    promises.push(loadNewsData())
    
    // 加载课程统计
    promises.push(loadCourseData())
    
    // 加载会议统计
    promises.push(loadMeetingData())
    
    // 如果是管理员，加载用户统计
    if (userStore.isAdmin) {
      promises.push(loadUserData())
      promises.push(loadPendingData())
    }
    
    await Promise.all(promises)
    
  } catch (error) {
    console.error('加载仪表盘数据失败:', error)
    ElMessage.error('加载数据失败')
  } finally {
    loading.value = false
  }
}

// 加载新闻数据
const loadNewsData = async () => {
  try {
    // 获取新闻统计
    const statsResponse = await get('/news/list', { page: 1, pageSize: 1 })
    if (statsResponse.code === 200) {
      statsData.news.total = statsResponse.data.total
    }
    
    // 获取最新新闻
    const newsResponse = await get('/news/list', { page: 1, pageSize: 4 })
    if (newsResponse.code === 200) {
      recentNews.value = newsResponse.data.list || []
      
      // 统计各状态数量
      const allNewsResponse = await get('/news/list', { page: 1, pageSize: 1000 })
      if (allNewsResponse.code === 200) {
        const allNews = allNewsResponse.data.list || []
        statsData.news.pending = allNews.filter(item => item.status === 0).length
        statsData.news.published = allNews.filter(item => item.status === 1).length
      }
    }
  } catch (error) {
    console.error('加载新闻数据失败:', error)
  }
}

// 加载课程数据
const loadCourseData = async () => {
  try {
    const response = await get('/course/list', { page: 1, pageSize: 1000 })
    if (response.code === 200) {
      const courses = response.data.list || []
      statsData.courses.total = response.data.total
      statsData.courses.pending = courses.filter(item => item.status === 0).length
      statsData.courses.published = courses.filter(item => item.status === 1).length
    }
  } catch (error) {
    console.error('加载课程数据失败:', error)
  }
}

// 加载会议数据
const loadMeetingData = async () => {
  try {
    const response = await get('/meeting/list', { page: 1, pageSize: 1000 })
    if (response.code === 200) {
      const meetings = response.data.list || []
      statsData.meetings.total = response.data.total
      statsData.meetings.pending = meetings.filter(item => item.status === 0).length
      statsData.meetings.published = meetings.filter(item => item.status === 1).length
    }
  } catch (error) {
    console.error('加载会议数据失败:', error)
  }
}

// 加载用户数据
const loadUserData = async () => {
  try {
    const response = await get('/user/list', { page: 1, pageSize: 1000 })
    if (response.code === 200) {
      const users = response.data.list || []
      statsData.users.total = response.data.total
      statsData.users.active = users.filter(item => item.status === 1).length
      statsData.users.disabled = users.filter(item => item.status === 0).length
    }
  } catch (error) {
    console.error('加载用户数据失败:', error)
  }
}

// 加载待审核数据
const loadPendingData = async () => {
  try {
    // 获取待审核新闻
    const newsResponse = await get('/news/pending', { page: 1, pageSize: 1 })
    if (newsResponse.code === 200) {
      pendingStats.news = newsResponse.data.total
    }
    
    // 获取待审核课程
    const courseResponse = await get('/course/pending', { page: 1, pageSize: 1 })
    if (courseResponse.code === 200) {
      pendingStats.courses = courseResponse.data.total
    }
    
    // 获取待审核会议
    const meetingResponse = await get('/meeting/pending', { page: 1, pageSize: 1 })
    if (meetingResponse.code === 200) {
      pendingStats.meetings = meetingResponse.data.total
    }
  } catch (error) {
    console.error('加载待审核数据失败:', error)
  }
}

onMounted(() => {
  loadDashboardData()
})
</script>

<style scoped>
.dashboard {
  max-width: 1200px;
  margin: 0 auto;
}

.welcome-card {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 12px;
  padding: 30px;
  color: white;
  margin-bottom: 24px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.welcome-content h2 {
  margin: 0 0 8px 0;
  font-size: 24px;
  font-weight: 600;
}

.welcome-content p {
  margin: 0;
  opacity: 0.9;
  font-size: 14px;
}

.welcome-actions {
  display: flex;
  gap: 12px;
}

.welcome-actions .el-button {
  background: rgba(255, 255, 255, 0.2);
  border: 1px solid rgba(255, 255, 255, 0.3);
  color: white;
}

.welcome-actions .el-button:hover {
  background: rgba(255, 255, 255, 0.3);
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 20px;
  margin-bottom: 24px;
}

.stat-card {
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  display: flex;
  align-items: center;
  transition: transform 0.3s ease, box-shadow 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 16px;
  font-size: 24px;
  color: white;
}

.stat-icon.news {
  background: linear-gradient(135deg, #409EFF, #337ecc);
}

.stat-icon.course {
  background: linear-gradient(135deg, #67C23A, #529b2e);
}

.stat-icon.meeting {
  background: linear-gradient(135deg, #E6A23C, #b88230);
}

.stat-icon.user {
  background: linear-gradient(135deg, #F56C6C, #c45656);
}

.stat-content {
  flex: 1;
}

.stat-number {
  font-size: 28px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 4px;
}

.stat-label {
  color: #606266;
  font-size: 14px;
  margin-bottom: 4px;
}

.stat-extra {
  font-size: 12px;
}

.stat-extra .pending {
  color: #E6A23C;
}

.stat-extra .active {
  color: #67C23A;
}

.dashboard-grid {
  display: grid;
  grid-template-columns: 2fr 1fr;
  gap: 20px;
  margin-bottom: 24px;
}

.chart-card,
.list-card {
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 12px;
  border-bottom: 1px solid #EBEEF5;
}

.card-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.chart-container {
  height: 300px;
}

.chart {
  height: 100%;
  width: 100%;
}

.list-content {
  max-height: 300px;
  overflow-y: auto;
}

.list-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 0;
  border-bottom: 1px solid #F5F7FA;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.list-item:hover {
  background-color: #F5F7FA;
  margin: 0 -12px;
  padding: 12px;
  border-radius: 6px;
}

.list-item:last-child {
  border-bottom: none;
}

.item-content {
  flex: 1;
}

.item-title {
  font-size: 14px;
  color: #303133;
  margin-bottom: 6px;
  font-weight: 500;
}

.item-meta {
  display: flex;
  align-items: center;
  gap: 12px;
  font-size: 12px;
  color: #909399;
}

.item-actions {
  color: #C0C4CC;
}

.bottom-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
}

.quick-actions-card,
.pending-card {
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.quick-actions {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 16px;
}

.action-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
  border: 2px dashed #DCDFE6;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.action-item:hover {
  border-color: #409EFF;
  background-color: #F0F9FF;
}

.action-icon {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  background: #409EFF;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 8px;
  font-size: 20px;
}

.action-text {
  font-size: 14px;
  color: #606266;
  font-weight: 500;
}

.pending-list {
  space-y: 12px;
}

.pending-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px;
  background: #FFF7E6;
  border: 1px solid #FFE58F;
  border-radius: 6px;
  margin-bottom: 12px;
}

.pending-info {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #D46B08;
  font-size: 14px;
}

.no-pending {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  color: #67C23A;
  font-size: 14px;
  padding: 20px;
}

.empty-state {
  padding: 40px 0;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .welcome-card {
    flex-direction: column;
    text-align: center;
    gap: 20px;
  }
  
  .stats-grid {
    grid-template-columns: 1fr;
  }
  
  .dashboard-grid {
    grid-template-columns: 1fr;
  }
  
  .bottom-grid {
    grid-template-columns: 1fr;
  }
  
  .quick-actions {
    grid-template-columns: 1fr;
  }
  
  .stat-card {
    flex-direction: column;
    text-align: center;
  }
  
  .stat-icon {
    margin-right: 0;
    margin-bottom: 12px;
  }
}

@media (max-width: 480px) {
  .dashboard {
    padding: 0 10px;
  }
  
  .welcome-card,
  .chart-card,
  .list-card,
  .quick-actions-card,
  .pending-card {
    padding: 16px;
  }
}
</style>